package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.controller.utils.FileUploadUtil;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController{
    // 注入service:import com.alibaba.dubbo.config.annotation.Reference;
    @Reference
    private FactoryService factoryService;
    @Reference
    private ContractProductService contractProductService;

    /**
     * 1.购销合同列表，点击货物进入project-list.jsp货物列表和添加货物的页面
     * 请求地址：http://localhost:8080/cargo/contractProduct/list.do?contractId=1
     * 响应地址：/WEB-INF/pages/cargo/product/product-list.jsp
     */
    @RequestMapping("/list")
    public String list(
            String contractId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize){

        //1.1 查询货物的工厂
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //1.2 存储工厂
        request.setAttribute("factoryList",factoryList);

        //1.3 根据购销合同的id，查询购销合同下的所有货物
        ContractProductExample cpExample = new ContractProductExample();
        cpExample.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo =
                contractProductService.findByPage(cpExample, pageNum, pageSize);
        //1.4 存储货物列表
        request.setAttribute("pageInfo",pageInfo);

        //1.5 存储购销合同id  (project-list.jsp是货物列表也是添加货物页面，添加货物要有购销合同id)
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-list";
    }

    // 注入文件上传工具类
    @Autowired
    private FileUploadUtil fileUploadUtil;
    /**
     * 2. 保存或者修改货物
     *  <input type="file" name="productPhoto" >
     */
    @RequestMapping("/edit")
    public String edit(MultipartFile productPhoto, ContractProduct contractProduct) throws Exception {
        contractProduct.setCompanyId(getLoginCompanyId());
        contractProduct.setCompanyName(getLoginCompanyName());

        // 3.1 根据主键id判断添加或者修改
        if (StringUtils.isEmpty(contractProduct.getId())){
            if (productPhoto != null){
                String productImage = "http://" + fileUploadUtil.upload(productPhoto);
                contractProduct.setProductImage(productImage);
            }
            // 3.1 执行添加操作
            contractProductService.save(contractProduct);
        } else {
            // 3.2 执行修改操作
            contractProductService.update(contractProduct);
        }
        // 3.3 操作成功，返回到购销合同列表
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();
    }

    /**
     * 3. 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        // 查询货物的工厂
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        // 根据购销合同id查询
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        return "cargo/product/product-update";
    }

    /**
     * 4. 删除货物
     * @param id            根据id删除
     * @param contractId    删除后重定向到货物列表和添加页面（product-list.jsp）
     * @return
     */
    @RequestMapping("/delete")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    /**
     * 5. 货物导入
     * 请求地址：http://xx:8080/cargo/contractProduct/toImport.do?contractId=1
     * 响应地址：/WEB-INF/pages/cargo/product/product-import.jsp
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    /**
     * 6. 导入货物信息
     * 请求地址：/cargo/contractProduct/import.do
     * 请求参数：contractId
     */
    @RequestMapping("/import")
    public String importExcel(MultipartFile file,String contractId) throws Exception {

        // 加载文件流，创建工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        // 获取工作表
        Sheet sheet = workbook.getSheetAt(0);

        // 获取登陆用户所属公司信息
        String loginCompanyId = getLoginCompanyId();
        String loginCompanyName = getLoginCompanyName();

        // 遍历工作表的所有行，从第二行开始遍历。 第二行的索引是1
        for (int i=1; i<sheet.getPhysicalNumberOfRows(); i++){
            // 获取每一行
            Row row = sheet.getRow(i);

            // 获取每一行的每一列，设置到货物对象中
            ContractProduct cp = new ContractProduct();
            // 货物对象-设置企业信息
            cp.setCompanyId(loginCompanyId);
            cp.setCompanyName(loginCompanyName);
            // 货物对象-设置购销合同id
            cp.setContractId(contractId);
            //导出数据格式：生产厂  货号	 数量  包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求
            cp.setFactoryName(row.getCell(1).getStringCellValue());
            cp.setProductNo(row.getCell(2).getStringCellValue());
            cp.setCnumber((int) row.getCell(3).getNumericCellValue());
            cp.setPackingUnit(row.getCell(4).getStringCellValue());
            cp.setLoadingRate(row.getCell(5).getNumericCellValue() + "");
            cp.setBoxNum((int) row.getCell(6).getNumericCellValue());
            cp.setPrice(row.getCell(7).getNumericCellValue());
            cp.setProductDesc(row.getCell(8).getStringCellValue());
            cp.setProductRequest(row.getCell(9).getStringCellValue());

            // 执行保存
            contractProductService.save(cp);
        }

        // 释放资源
        workbook.close();
        // 保存购销合同id
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }
}

















